package yuan.deng.dao.impl;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import yuan.deng.dao.UserDao;
import yuan.deng.domain.User;
import yuan.deng.utils.DataSourceUtils;
import yuan.deng.utils.JDBCUtlis;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
public class UserDaoImpl implements UserDao {
    JdbcTemplate jdbcTemplate=new JdbcTemplate(DataSourceUtils.getDataSource());
    private Connection connection=null;//连接对象
    private PreparedStatement ps=null;//预定义操作对象
    private ResultSet resultSet=null;//结果集对象
    @Override
    public int addUser(User user) {
        int i=0;
        try {
            connection= JDBCUtlis.getConn();//获取连接
            ps = connection.prepareStatement("insert into user values(?,?,?,?,?)");//预定义操作对象
            ps.setInt(1,user.getId());//给？赋值
            ps.setString(2,user.getName());
            ps.setInt(3,user.getAge());
            ps.setString(4,user.getSex());
            ps.setFloat(5,user.getMoney());
            i = ps.executeUpdate();//返回增加结果
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtlis.close(connection,ps);
        }
        return i;
    }

    @Override
    public void delUser(int id) {
        jdbcTemplate.update("delete from user where id = ? ", id);
    }

    @Override
    public List<User> findAll() {
        List<User> users=null;
        try {
            users = jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
            return users;
        }catch (Exception e){
            return users;}

    }
}
